<template>
	<div class="addProject business-workAdd">
		<div class="addForm zll-form">
			<el-form :model="addForm" :rules="rules" ref="addForm" class="demo-ruleForm">
				<el-row :gutter="40" v-if="type == 'see'">
					<el-col :span="8">
						<el-form-item class="formList" prop="procureCode" label="采购号：">
							<el-input clearable class="input_right" v-model="addForm.procureCode" disabled></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row :gutter="40">
					<el-col :span="8">
						<el-form-item class="formList" prop="procureType" label="采购类型：">
							<el-select clearable class="input_right" v-model="addForm.procureType"
									   :disabled="type == 'see'">
								<el-option label="合同" value="1"></el-option>
								<el-option label="报销" value="2"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item class="formList" prop="processName" label="大类：">
							<el-select clearable class="input_right" v-model="addForm.processName"
									   :disabled="type == 'see'" @change="changeItemValue">
								<el-option :label="key" :value="key" v-for="(value,key) in itemMaps"
										   :key="key"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item class="formList" prop="procureTime" label="采购日期：">
							<el-date-picker v-model="addForm.procureTime" type="date" class="input_right"
											format="yyyy-MM-dd"
											value-format="yyyy-MM-dd"
											:disabled="type == 'see'"
											placeholder="请选择采购日期">
							</el-date-picker>
						</el-form-item>
						<el-form-item class="formList" prop="supplier" label="供应商：">
							<el-input clearable class="input_right" v-model="addForm.supplier"
									  :disabled="type == 'see'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="type == 'see'">
						<el-form-item class="formList" prop="procureStatus" label="状态：">
							<el-input clearable class="input_right" v-model="addForm.procureStatusCn"
									  :disabled="type == 'see'"></el-input>
						</el-form-item>
						<el-form-item class="formList" prop="procureUser" label="采购人：">
							<el-input clearable class="input_right" v-model="addForm.procureUser"
									  :disabled="type == 'see'"></el-input>
						</el-form-item>
					</el-col>
				</el-row>
				<div v-if="type=='add'">
					<div class="con_p">
						<div class="mine-add">
							<span class="tipss">单次下单最多5个采购任务</span>
							<span @click="addTable()"><i class="el-icon-circle-plus"></i></span>
							<span @click.stop="batchDelete()"><i class="el-icon-remove-outline"></i></span>
						</div>
					</div>
					<div class="tableList">
						<table border="1">
							<tr>
								<th width="40"></th>
								<th>品类</th>
								<th>物料代码</th>
								<th>物料名称</th>
								<th width="150">品牌规格</th>
								<th>单位</th>
								<th>采购数量</th>
								<th>单价</th>
								<th>合计</th>
								<th width="60"></th>
							</tr>
							<tr v-if="tableList.length == 0" class="noData">
								<td colspan="10">暂无数据</td>
							</tr>
							<tr v-else class="add_Table" v-for="(item, index) in tableList" :key="index">
								<td width="40">
									<el-checkbox v-model="item.checked"></el-checkbox>
								</td>
								<td>
									<el-select v-model="item.itemId" placeholder="" class="text_center" clearable
											   :disabled="type == 'see'" @change="changeMaterial(item)">
										<el-option :label="ita.name" :value="ita.categoryId"
												   v-for="(ita,index) in materialItems" :key="ita.name"></el-option>
									</el-select>
								</td>
								<td>
									<el-select v-model="item.materialId" placeholder="" class="text_center" clearable
											   :disabled="type == 'see'"  @change="chooseMaterial(item)">
										<el-option :label="ma.materialName" :value="ma.id"
												   v-for="(ma,index) in materials" :key="ma.id"></el-option>
									</el-select>
								</td>
								<td>
									<el-input v-model="item.materialCode" placeholder="" class="text_center" clearable
											  disabled></el-input>
								</td>
								<td>
									<el-input v-model="item.materialGrade" placeholder="" class="text_center" clearable
											  disabled></el-input>
								</td>
								<td><p>{{item.measureUnit}}</p></td>
								<td>
									<el-input v-model="item.procureCount"
											  @input="item.procureCount=item.procureCount.replace(/[^0-9\.]/g,'')"
											  placeholder="" class="text_center" clearable
											  :disabled="type == 'see'" @change="totalPriceChange(item)"></el-input>
								</td>
								<td>
									<el-input v-model="item.procurePrice"
											  @input="item.procurePrice=item.procurePrice.replace(/[^0-9\.]/g,'')"
											  placeholder="" class="text_center" clearable
											  :disabled="type == 'see'" @change="totalPriceChange(item)"></el-input>
								</td>
								<td><p>{{item.procureTotalPrice}}</p></td>
								<td width="60">
									<span class="edit" @click.stop="deleteTable(item,index)">删除</span>
								</td>
							</tr>
						</table>
					</div>
				</div>
				<div v-else>
					<div class="tableList" style="margin-top: 0;">
						<table border="1">
							<tr>
								<th>品类</th>
								<th>物料代码</th>
								<th>物料名称</th>
								<th width="150">品牌规格</th>
								<th>单位</th>
								<th>采购数量</th>
								<th>单价</th>
								<th>合计</th>
							</tr>
							<tr class="add_Table">
								<td><p>{{ materialDetail.itemAlias }}</p></td>
								<td><p>{{ materialDetail.materialCode }}</p></td>
								<td><p>{{ materialDetail.materialName }}</p></td>
								<td><p>{{ materialDetail.materialGrade }}</p></td>
								<td><p>{{ materialDetail.measureUnit }}</p></td>
								<td><p>{{ materialDetail.procureCount }}</p></td>
								<td><p>{{ materialDetail.procurePrice }}</p></td>
								<td><p>{{ materialDetail.procureTotalPrice }}</p></td>
							</tr>
						</table>
					</div>
				</div>
			</el-form>
		</div>
	</div>
</template>
<script>
	import {getStore} from "@/plugins/localStore";
	import {formatDate} from "@/plugins/formatDate";

	export default {
		props: ['editData', 'type'],
		data() {
			return {
				addForm: {
					id: '',
					procureCode: '',
					procureType: '',
					processName: '',
					supplier: '',
					procureTime: '',
					procureUser: '',
					procureStatus: '',
					procureStatusCn: '',
					remark: '',
				},
				materialDetail:{},
				tableList: [],
				rules: {
					procureType: [
						{required: true, message: '请选择采购类型', trigger: 'change'},
					],
					processName: [
						{required: true, message: '请选择大类', trigger: 'change'},
					],
					procureTime: [
						{required: true, message: '请选择采购日期', trigger: 'change'},
					],
					supplier: [
						{required: true, message: '请选择供应商', trigger: 'change'},
					],
				},

				itemMaps: {},
				materialItems: [],
				materials: [],
				user:{}
			}
		},
		methods: {
			addTable() {
				if (this.tableList.length < 5) {
					this.tableList.push(
						{
							id:'',
							checked:false,
							itemId:'',
							materialId:'',
							materialName:'',
							materialCode:'',
							materialGrade:'',
							measureUnit:'',
							procurePrice:'',
							procureCount:'',
							procureTotalPrice:'',
						},
					);
				} else {
					this.$notify({title: '提示', message: "单次下单最多5个采购任务", type: 'warning'});
				}
			},
			batchDelete() {
				let filter = this.tableList.filter((item) => !item.checked);
				this.tableList = JSON.parse(JSON.stringify(filter))
			},

			deleteTable(item, index) {//删除table
				this.tableList.splice(index, 1);
			},
			submitForm(val, type) {
				let self = this;
				if(self.tableList.length == 0){
					self.$message.warning('请添加采购任务！');
					return;
				}
				self.$refs["addForm"].validate((valid) => {
					if (valid) {
						for (let data of self.tableList) {
							if (!data.itemId) {
								self.$message.warning('请选择品类');
								return -1;
							} else if (!data.materialId) {
								self.$message.warning('请选择物料代码');
								return -1;
							}  else if (!data.materialGrade) {
								self.$message.warning('请输入包装规格');
								return -1;
							} else if (!data.procureCount) {
								self.$message.warning('请输入数量(袋)');
								return -1;
							} else if (!data.procurePrice) {
								self.$message.warning('请输入单价');
								return -1;
							}
						}
						self.operate(val);
					} else {
						return false;
					}
				});

			},

			operate() {
				let self = this;
				let param = Object.assign({},this.addForm);
				param.procureStorages = this.tableList;
				if (self.count == 0) {
					self.$http({
						url: '/jinl/procure/addProcure',
						method: "post",
						data: JSON.stringify(param),
						dataType: 'json',
						contentType: "application/json",
					}).then(resp => {
						if (resp.success) {
							self.$notify({title: '提示', message: "操作成功！", type: 'success'});
							self.count--;
							self.$emit("refreshPage");
							return;
						}
						self.$notify({title: '提示', message: resp.message, type: 'error'});
						self.count--;
					});
					self.count++;
				}
			},

			getMaterialByGroupBigTypeId() {
				let self = this;
				self.itemMaps = {};
				self.$http({
					url: "/jinl/material/getMaterialByGroupBigTypeId",
					method: "post",
				}).then(resp => {
					if (resp.success) {
						self.itemMaps = resp.result;
						console.log(self.itemMaps)
					}
				});
			},

			changeItemValue() {
				this.tableList = [];
				this.addTable();
				this.materials = [];
				this.materialItems = [];
				if(!this.addForm.processName){
					return;
				}
				let items = this.itemMaps[this.addForm.processName];
				let materials = [];
				for (let m of items) {
					let caId = m.categoryId;
					let existIndex = materials.findIndex((mm) => mm.categoryId == caId);
					if (existIndex < 0) {
						let obj = {name: m.itemAlias, categoryId: caId, children: [m]};
						materials.push(obj);
					} else {
						materials[existIndex].children.push(m);
					}
				}
				this.materials = [];
				this.materialItems = materials;

			},

			changeMaterial(item){
				this.materials = [];
				item.materialId = '';
				item.materialCode = '';
				item.measureUnit = '';
				item.formatMaterial = '';
				let index = this.materialItems.findIndex((mm) =>mm.categoryId == item.itemId);
				if(index > -1){
					this.materials = this.materialItems[index].children;
				}
				console.log(this.materials)
			},

			chooseMaterial(item){
				let index = this.materials.findIndex((mm) =>mm.id == item.materialId);
				console.log(index)
				if(index < 0){
					return;
				}
				item.materialCode = this.materials[index].materialCode;
				item.measureUnit = this.materials[index].measureUnit;
				item.materialGrade = this.materials[index].formatMaterial;
			},

			totalPriceChange(item){
				if(item.procurePrice && item.procureCount){
					let totalPrice = parseFloat(item.procurePrice) *   parseFloat(item.procureCount);
					item.procureTotalPrice = totalPrice.toFixed(1);
				}else{
					item.procureTotalPrice = '';
				}
			},

		},

		watch:{
			editData(val) {
				console.log('======editData=========')
				console.log(val)
				this.user = getStore();
				this.count = 0;
				for (let key in  this.addForm) {
					this.addForm[key] = val[key] || ''
				}
				if (this.type == 'add' ) {
					let self = this;
					self.addForm.procureUser = this.user.userName;
					self.$nextTick(() => {
						self.addTable();
					});
				}else{
					this.materialDetail = val;
				}
			},
		},

		mounted() {
			this.getMaterialByGroupBigTypeId();
		},
		components: {},
	}
</script>
<style lang="scss" scoped>
	@import "@/style/dialog.scss";

	.edit {
		color: #1890ff;
		padding: 0 5px;
		cursor: pointer;

		&.icons {
			font-size: 16px;
		}

		&:hover {
			opacity: .7;
		}
	}

	.formList {
		margin-bottom: 8px !important;
	}
</style>